#coding=utf-8
import StringIO
import logging

from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

class File(db.Model):
    uuid = db.StringProperty(required=True)
    name = db.StringProperty(required=True)
    mime = db.StringProperty()
    size = db.IntegerProperty()
    created = db.DateTimeProperty(auto_now_add=True)
    
class FileContent(db.Model):
    file = db.ReferenceProperty(File)
    
    data = db.BlobProperty()
    sn = db.IntegerProperty()
    
class FileHandler(webapp.RequestHandler):
    def post(self):
        uuid = self.request.get("name")
        name = self.request.get("name")
        content = self.request.get("file")
        
        size = len(content)
        mime = self.request.body_file.vars['file'].headers['content-type']
        
        f = File(key_name=name, name=name, mime=mime, size=size)
        f.put()
        
        #split file data
        chunk_size = 1000 * 1000
        i = 1
        data = content 
        while True:
            if data:
                head, data = data[:chunk_size], data[chunk_size:]
                fc = FileContent(file=f, data=db.Blob(head), sn=i)
                fc.put()
                
                i = i + 1
            else:
                break              
        self.response.out.write("Put File into DataStore Sucessfully!\n")
    
    def get(self):
        name = self.request.get('name')      
        f = File.gql("WHERE name = :1", name).fetch(1)[0]

        if not f:
            self.error(404)
            return self.response.out.write('File %s:404 not found'%name)
        
        self.response.headers['Content-Type'] = str(f.mime) 
        
        content_disposition = 'attachment; filename="%s"' % f.name.encode('u8')
        self.response.headers['Content-Disposition'] = content_disposition
        
        s = StringIO.StringIO()
        q = FileContent.gql('WHERE file=:1 order by sn', f)
        for fc in q:
            s.write(fc.data)
            
        self.response.out.write(s.getvalue())

class JustForTest(webapp.RequestHandler):
    def post(self):
        name = self.request.get('name')
        self.response.out.write(str(type(name)))
        self.response.out.write('\n')

    def get(self):
        name = self.request.get('name')
        self.response.out.write(str(type(name)))
        self.response.out.write('\n')
        
application = webapp.WSGIApplication([('/', FileHandler),
                                      ('/test/', JustForTest),],
                                     debug=True)

def main():
  run_wsgi_app(application)

if __name__ == "__main__":
  main()
